/**
 * 认证中间件
 */
import { NextRequest, NextResponse } from 'next/server';
import { AuthService, TokenPayload } from '@/lib/auth';

// 需要认证的路由前缀
const PROTECTED_ROUTES = [
  '/api/user',
  '/api/admin',
  '/api/profile',
  // '/api/auth/me', // 移除，让该路由自行处理认证
  // '/api/generation-records',
  // '/api/templates/create',
  // '/api/templates/update',
  // '/api/templates/delete'
];

// 公开路由（不需要认证）
const PUBLIC_ROUTES = [
  '/api/auth/login',
  '/api/auth/register',
  '/api/auth/refresh',
  '/api/auth/me',
  '/api/health',
  '/api/models/list',
  '/api/sd/status'
];

// 管理员专用路由
const ADMIN_ROUTES = [
  '/api/admin',
  // '/api/users/manage',
  // '/api/system'
];

export interface AuthenticatedRequest extends NextRequest {
  user?: TokenPayload;
}

/**
 * 认证中间件函数
 */
export async function authMiddleware(request: NextRequest): Promise<NextResponse | null> {
  const { pathname } = request.nextUrl;

  // 检查是否为公开路由
  if (isPublicRoute(pathname)) {
    return null; // 继续处理请求
  }

  // 检查是否需要认证
  if (!isProtectedRoute(pathname)) {
    return null; // 不需要认证，继续处理
  }

  // 获取token
  const token = extractToken(request);
  if (!token) {
    return createUnauthorizedResponse('缺少认证token');
  }

  // 验证token
  const verification = await AuthService.verifyToken(token);
  if (!verification.valid || !verification.payload) {
    return createUnauthorizedResponse(verification.message || 'Token无效');
  }

  // 检查管理员权限
  if (isAdminRoute(pathname) && verification.payload.role !== 'admin') {
    return createForbiddenResponse('需要管理员权限');
  }

  // 将用户信息添加到请求头中，供API路由使用
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-user-id', verification.payload.userId);
  requestHeaders.set('x-user-email', verification.payload.email);
  requestHeaders.set('x-user-role', verification.payload.role);

  // 创建新的请求对象
  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });

  return response;
}

/**
 * 从请求中提取token
 */
function extractToken(request: NextRequest): string | null {
  // 从Authorization header中获取
  const authHeader = request.headers.get('authorization');
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.substring(7);
  }

  // 从cookie中获取
  const tokenCookie = request.cookies.get('auth-token');
  if (tokenCookie) {
    return tokenCookie.value;
  }

  return null;
}

/**
 * 检查是否为公开路由
 */
function isPublicRoute(pathname: string): boolean {
  return PUBLIC_ROUTES.some(route => pathname.startsWith(route));
}

/**
 * 检查是否为受保护路由
 */
function isProtectedRoute(pathname: string): boolean {
  return PROTECTED_ROUTES.some(route => pathname.startsWith(route));
}

/**
 * 检查是否为管理员路由
 */
function isAdminRoute(pathname: string): boolean {
  return ADMIN_ROUTES.some(route => pathname.startsWith(route));
}

/**
 * 创建未授权响应
 */
function createUnauthorizedResponse(message: string): NextResponse {
  return NextResponse.json(
    { error: message, code: 'UNAUTHORIZED' },
    { status: 401 }
  );
}

/**
 * 创建禁止访问响应
 */
function createForbiddenResponse(message: string): NextResponse {
  return NextResponse.json(
    { error: message, code: 'FORBIDDEN' },
    { status: 403 }
  );
}

/**
 * API路由中获取当前用户信息的辅助函数
 */
export function getCurrentUser(request: NextRequest): TokenPayload | null {
  const userId = request.headers.get('x-user-id');
  const email = request.headers.get('x-user-email');
  const role = request.headers.get('x-user-role');

  if (!userId || !email || !role) {
    return null;
  }

  return {
    userId,
    email,
    role
  };
}

/**
 * 检查用户是否有管理员权限
 */
export function isAdmin(user: TokenPayload | null): boolean {
  return user?.role === 'admin';
}

/**
 * 检查用户是否为资源所有者或管理员
 */
export function canAccessResource(user: TokenPayload | null, resourceUserId: string): boolean {
  if (!user) return false;
  return user.userId === resourceUserId || user.role === 'admin';
}

export default authMiddleware;